package com.lucas.rpc.framework.proxy;

import com.lucas.rpc.common.rpc.interfaces.HelloService;
import com.lucas.rpc.framework.loadbalance.RandomLoadBalance;
import com.lucas.rpc.framework.register.remote.MapRemoteRegister;
import com.lucas.rpc.framework.remote.RpcRequest;
import com.lucas.rpc.framework.remote.URL;
import com.lucas.rpc.framework.transport.tomcat.TomcatClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-11-28 14:13
 **/
public class ProxyFactory {

    public static<T> T getProxy(Class interfaceClass,String version){
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(),
                new Class[]{interfaceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        RpcRequest rpcRequest = new RpcRequest(interfaceClass.getName() ,
                                method.getName(),args,method.getParameterTypes(),version);

                        TomcatClient tomcatClient = new TomcatClient();

                        //服务发现
                        List<URL> urLs = MapRemoteRegister.getURLs(interfaceClass.getName());

                        //负载均衡
                        URL url = RandomLoadBalance.selectURL(urLs);

                        String result = tomcatClient.send(url.getHostname(), url.getPort(), rpcRequest);
                        return result;
                    }
                });

        return (T)proxyInstance;
    }
}
